package com.demo.oss.service.impl;



import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.Bucket;
import com.aliyun.oss.model.CannedAccessControlList;

import com.demo.oss.config.OssProperties;
import com.demo.oss.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.List;
import java.util.UUID;

@Service
@Slf4j
public class FileServiceImpl implements FileService {
    @Override
    public String upload(InputStream inputStream, String module, String fileName) {

        //创建OssClient实例
        OSS ossClient = new OSSClientBuilder().build(
                OssProperties.ENDPOINT,
                OssProperties.KEY_ID,
                OssProperties.KEY_SECRET
        );
        //判断oss实例是否存在,如果不存在则创建,如果存在则获取
        List<Bucket> buckets = ossClient.listBuckets();
        boolean b = ossClient.doesBucketExist(module);
        if(!ossClient.doesBucketExist(module)){
            //创建bucket
            ossClient.createBucket(module);
            //设置oss实例的访问权限
            ossClient.setBucketAcl(module, CannedAccessControlList.PublicRead);
        }
        // 上传文件流。
        // 文件目录结构
        //构建日期路径
        String timeFolder = new DateTime().toString("/yyyy/MM/dd/");
        //文件名生成
        fileName = UUID.randomUUID().toString() + fileName.substring(fileName.lastIndexOf("."));
        String key = module + timeFolder + fileName;
        ossClient.putObject(module, key, inputStream);


        // 关闭OSSClient。
        ossClient.shutdown();

        //文件的url地址
        //https:// bucketname   .  endpoint / + key
        return "https://" + module + "." + OssProperties.ENDPOINT + "/" + key;
    }

    @Override
    public void removeFile(String url) {

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(
                OssProperties.ENDPOINT,
                OssProperties.KEY_ID,
                OssProperties.KEY_SECRET);

//        String host = "https://" + module + "." + OssProperties.ENDPOINT + "/";
//        String objectName = url.substring(host.length());
//
//        // 删除文件。如需删除文件夹，请将ObjectName设置为对应的文件夹名称。如果文件夹非空，则需要将文件夹下的所有object删除后才能删除该文件夹。
        ossClient.deleteObject("mogu-blog", url);

        // 关闭OSSClient。
        ossClient.shutdown();
    }
}
